package org.http;

import lombok.extern.slf4j.Slf4j;
import org.http.request.HttpRequest;
import org.http.request.Request;
import org.http.response.HttpResponse;
import org.http.response.Response;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Map;

/**
 * @author andy
 */
@Slf4j
public class RequestHandlerBak implements Runnable {
    private  SelectionKey selectionKey;
    private  Map<Integer, SocketChannel> socketChannels;

    public RequestHandlerBak(SelectionKey selectionKey, Map<Integer, SocketChannel> socketChannels) {
        this.selectionKey = selectionKey;
        this.socketChannels = socketChannels;
    }

    @Override
    public void run() {

        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) selectionKey.channel();
            Request request = new HttpRequest();
            String body = ((HttpRequest) request).resolveRequestBody(socketChannel);

            Response response = new HttpResponse(request, socketChannel);

            if (body != null) {
                request.setCharEncoding(Const.encoding);
                socketChannel.shutdownInput();
                dynamicService(request, response);
                response.response();
            }

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                selectionKey.cancel();
                if(null != socketChannel){
                    socketChannels.remove(socketChannel.hashCode());
                    socketChannel.finishConnect();
                    socketChannel.close();
                    PrintInfo.of().printInfo(socketChannel);
                }
                socketChannel = null;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    private void dynamicService(Request request, Response response){
//        response.setResponseCode(200);
    }
}
